package com.weipai.springboot.module.service.impl;

import com.sun.tools.doclets.formats.html.SourceToHTMLConverter;
import com.weipai.springboot.module.service.FileUploadService;
import com.weipai.springboot.module.util.FileUploadUtil;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.slf4j.Logger;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

@Service
public class FileUploadServiceImpl implements FileUploadService {
	
	private final static Logger logger = LoggerFactory.getLogger(FileUploadServiceImpl.class);
	

	@Override
	public String saveFileUpload(HttpServletRequest request, MultipartFile file) {
		String uploadStatus = null;
		try{
			//获取文件后缀
			String fileName= file.getOriginalFilename();
			String houzhui = fileName.substring(fileName.lastIndexOf('.')+1);
			//给文件添加uuid名字
			String newFileName = UUID.randomUUID().toString().replaceAll("-", "");
			houzhui = houzhui.toLowerCase();
			// 上传文件的格式限制	       
			//if (!"pdf".equals(houzhui) ) {
			//	return "formatError";
			//}
			//设置文件存放路径
//			FileUtil fileUtil = new FileUtil();
//			StringBuffer newFilePath = fileUtil.getFilePackagePath();  //生成年、月、日 目录
//			String filePath = FileUploadBean.getFILE_SAVE_BASE()+newFilePath;
//			File imgFile = new File(filePath);
//			// 如果目录不存在，自动创建
//			if (!imgFile.isDirectory()) {
//				imgFile.mkdirs();
//			}
//			//上传原文件
//			FileOutputStream fs = new FileOutputStream(filePath + "/"+ newFileName+"."+houzhui); 
//			InputStream stream = file.getInputStream();
//	        byte[] buffer = new byte[1024*1024];      
//	        int byteread = 0;
//	        while ((byteread=stream.read(buffer))!=-1){      
//	           fs.write(buffer,0,byteread);    
//	           fs.flush();
//	        }     
//	        fs.close();    
//	        stream.close(); 	
//	        
//	        //将文件上传到阿里云OSS
//	        MyOSSClient oss = new MyOSSClient();
//	        File saveJSFile = new File(filePath + newFileName+"."+houzhui);
//	        String jSkey = newFileName+"."+houzhui;
//	        oss.upload(jSkey, saveJSFile);
//		    saveJSFile.delete();
//	        
//	        //保存上传文件信息
//			fileUp.setName(newFileName);
//			fileUp.setSourceName(fileName);
//			fileUp.setSuffix(houzhui);
//			fileUp.setSize(file.getSize());
//			//fileUp.setUserAcc(fileBean.getUserAcc());
//			uploadStatus = newFileName+"."+houzhui;			
//			fileUp.setFilePath(uploadStatus);
//			fileUp.setCtsStr(DateUtils.timeFormat(System.currentTimeMillis()));
////				imgUploadDao.save(fileUp);
////				将保存记录保存到表中
//			fileUploadDao.save(fileUp);
			uploadStatus = FileUploadUtil.ImgSave(request, file);
		} catch (Exception e) {
			logger.error("服务器内部错误{}", e);
			uploadStatus = "error";
		}
		return uploadStatus;
	}

	@SuppressWarnings("static-access")
	@Override
	public String saveImgUpload(HttpServletRequest request , MultipartFile file) {
		String uploadStatus = null;
		try {
			String img_Name = file.getOriginalFilename().toLowerCase();
			String imgName = UUID.randomUUID().toString().replaceAll("-", "");
			//获取文件后缀
			String doto = img_Name.substring(img_Name.lastIndexOf(".")+1);
			String newImgName = imgName+"."+doto;
			// 设置文件大小限制不能超过5M
			// 设置文件大小限制不能超过150kb
//			if(file.getSize()>5*1024*1024){

			if(file.getSize()>150000){
				return "sizeover";
			}
			doto = doto.toLowerCase();
			// 上传文件的格式限制	       
			if (!"gif".equals(doto) && !"jpg".equals(doto) && !"jpeg".equals(doto)
					&& !"bmp".equals(doto) && !"png".equals(doto)) {
				return "formatError";
			}
			//设置文件存放路径
			//FileUtil imgUtil = new FileUtil();
			//StringBuffer yuanFilePath = imgUtil.getImgPackagePath();
			//String imgPath = imgUtil.getFILE_SAVE_BASE() + yuanFilePath;
			//File imgFile = new File(imgPath);
			//if (!imgFile.isDirectory()) {
			//	imgFile.mkdirs();
			//}
			////上传原文件
			//FileOutputStream fs = new FileOutputStream(imgPath + "/"+ newImgName);
			//InputStream stream = file.getInputStream();
			//byte[] buffer = new byte[1024*1024];
			//int byteread = 0;
			//while ((byteread = stream.read(buffer))!=-1){
			//	fs.write(buffer, 0, byteread);
			//	fs.flush();
			//}
			//fs.close();
			//stream.close();
			//String minFileName = newImgName.substring(0, newImgName.lastIndexOf("."))+"_min."+doto;
			//imgUtil.compressPic(imgPath, imgPath, newImgName, minFileName,
			//		Integer.parseInt(imgUtil.getWIDTH_FILE_MIN()),
			//		Integer.parseInt(imgUtil.getHIGHT_FILE_MIN()),
			//		Boolean.parseBoolean(imgUtil.getZOOM_FILE()));
			////上传到 阿里云OSS
			//MyOSSClient ossClient = new MyOSSClient();
			//File img = new File(imgPath + "/"+ newImgName);
			//ossClient.upload(yuanFilePath + newImgName, img);
            //
			////删除本地缓存文件
			//img.delete();
			////保存上传文件信息
			//FileUp fileUp = new FileUp();
			//fileUp.setName(imgName);
			//fileUp.setSourceName(img_Name);
			//fileUp.setSuffix(doto);
			//fileUp.setSize(file.getSize());
			//fileUp.setFilePath(yuanFilePath + newImgName);
			//fileUp.setCtsStr(DateUtils.timeFormat(System.currentTimeMillis()));
			//fileUp.setMinName(minFileName);
			//fileUp.setMinImgPath(yuanFilePath + minFileName);
			//fileUploadDao.save(fileUp);
			uploadStatus = FileUploadUtil.ImgSave(request, file);
			//uploadStatus = yuanFilePath+newImgName;
		} catch (Exception e) {
			logger.error("服务器内部错误", e);
			uploadStatus = "error";
		}
		return uploadStatus;
	}

	@Override
	public String saveImgUpload(HttpServletRequest request, MultipartFile[] image) {
		StringBuffer sb = new StringBuffer();
		String a = "";
		if(image!=null&&image.length>0) {
			for (int i = 0; i < image.length; i++) {
				MultipartFile img =  image[i];
				a = saveImgUpload(request,img);
				if(image.length==1)
					sb.append(a);
				else
					sb.append(a+",");
			}
		}
		return new String(sb.substring(0,sb.length()));
	}

	@Override
	public String saveBaseUpload(HttpServletRequest request, MultipartFile file) {
		String uploadStatus = null;
		try {
			String img_Name = file.getOriginalFilename().toLowerCase();
			String imgName = UUID.randomUUID().toString().replaceAll("-", "");
			//获取文件后缀
			String doto = img_Name.substring(img_Name.lastIndexOf(".")+1);
			String newImgName = imgName+"."+doto;
			uploadStatus = FileUploadUtil.ImgSave(request, file);
		} catch (Exception e) {
			logger.error("服务器内部错误", e);
			uploadStatus = "error";
		}
		return uploadStatus;
	}


}
